package com.example.royalchef.view;

import android.content.Context;
import android.content.Intent;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.example.royalchef.R;
import com.example.royalchef.activity.HomeDetailActivity;
import com.example.royalchef.bean.SearchInfo;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;


/**
 * Created by yetwish on 2015-05-11
 */

public class SearchView extends LinearLayout implements View.OnClickListener {

    /**
     * 输入框
     */
    private EditText etInput;


    /**
     * 删除键
     */
    private ImageView ivDelete;

    /**
     * 返回按钮
     */
    private Button btnSearch;

    /**
     * 上下文对象
     */
    private Context mContext;

    /**
     * 弹出列表
     */
    private ListView lvTips;

    /**
     * 搜索回调接口
     */
    private String content;
    private ArrayList<String> list;
    private ArrayList<SearchInfo> searchInfos;
    public static final int SEARCHRESULT = 4;

    public SearchView(Context context, AttributeSet attrs) {
        super(context, attrs);
        mContext = context;
        LayoutInflater.from(context).inflate(R.layout.search_layout, this);
        initViews();
    }

    private void initViews() {
        etInput = (EditText) findViewById(R.id.search_et_input);
        ivDelete = (ImageView) findViewById(R.id.search_iv_delete);
        btnSearch = (Button) findViewById(R.id.search_btn_back);
        lvTips = (ListView) findViewById(R.id.search_lv_tips);
        etInput.addTextChangedListener(new Watcher());
        lvTips.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Intent intent = new Intent(getContext(), HomeDetailActivity.class);
                intent.putExtra("searchInfo", searchInfos.get(i));
                getContext().startActivity(intent);
                lvTips.setVisibility(View.GONE);
            }
        });

        ivDelete.setOnClickListener(this);
        btnSearch.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.search_et_input:
                lvTips.setVisibility(VISIBLE);
                break;
            case R.id.search_iv_delete:
                etInput.setText("");
                ivDelete.setVisibility(GONE);
                break;
            case R.id.search_btn_back:

                break;
        }
    }

    class MyAdapter extends BaseAdapter {
        private ArrayList<String> list;

        public MyAdapter(ArrayList<String> list) {
            this.list = list;
        }

        @Override
        public int getCount() {
            return list.size();
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder;
            if (convertView == null) {
                holder = new ViewHolder();
                convertView = View.inflate(getContext(), R.layout.search_item, null);
                holder.textView = (TextView) convertView.findViewById(R.id.tv_search_item);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            holder.textView.setText(list.get(position));
            return convertView;
        }

        class ViewHolder {
            TextView textView;
        }
    }

    class Watcher implements TextWatcher {

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            content = etInput.getText().toString().trim();
            RequestQueue queue = Volley.newRequestQueue(getContext());
            try {
                content = URLEncoder.encode(content, "utf-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            StringRequest stringRequest = new StringRequest(Request.Method.GET, "http://192.168.12.248:8080/cookbook/search.json?" + "search_cookbook=" + content,
                    new Response.Listener<String>() {
                        @Override
                        public void onResponse(String response) {
                            try {
                                JSONObject object = new JSONObject(response);
                                JSONArray data = object.getJSONArray("data");
                                searchInfos = new ArrayList<>();
                                for (int i = 0; i < data.length(); i++) {
                                    JSONObject jsonObject = data.getJSONObject(i);
                                    JSONObject user = jsonObject.getJSONObject("user");
                                    String nickname = user.getString("nickname");
                                    String title = jsonObject.getString("title");
                                    String cover = jsonObject.getString("cover");
                                    String content = jsonObject.getString("content");
                                    String createdat = jsonObject.getString("createdat");
                                    SearchInfo searchInfo = new SearchInfo(nickname, title, cover, content, createdat);
                                    searchInfos.add(searchInfo);
                                }
                                list = new ArrayList<>();
                                for (int i = 0; i < searchInfos.size(); i++) {
                                    list.add(searchInfos.get(i).getTitle());
                                }
                                MyAdapter adapter = new MyAdapter(list);
                                lvTips.setVisibility(VISIBLE);
                                lvTips.setAdapter(adapter);
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                }
            });
            queue.add(stringRequest);
        }

        @Override
        public void afterTextChanged(Editable s) {

        }
    }

}



